package com.hushan.elevator.service.impl;


import com.hushan.elevator.dao.DeviceMntRepository;
import com.hushan.elevator.model.DeviceMnt;
import com.hushan.elevator.model.User;
import com.hushan.elevator.security.SecurityUtils;
import com.hushan.elevator.service.DeviceMntService;
import jakarta.transaction.Transactional;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeviceMntServiceImpl implements DeviceMntService {

    private final DeviceMntRepository DeviceMntDao;

    @Autowired
    public DeviceMntServiceImpl(DeviceMntRepository DeviceMntRepository) {
        this.DeviceMntDao = DeviceMntRepository;
    }

    @Override
    public List<DeviceMnt> findAllDeviceMnt() {
        return DeviceMntDao.findAll();
    }

    @Override
    public DeviceMnt findDeviceMntById(Integer id) {
        return DeviceMntDao.findById(id).orElse(null);
    }

    @Override
    public List<DeviceMnt> findDeviceMntByDeviceId(Integer deviceId) {
        return DeviceMntDao.findByDeviceId(deviceId);
    }


    @Override
    public List<DeviceMnt> findDeviceMntByCreatedTimeBetween(LocalDateTime start, LocalDateTime end) {
        return DeviceMntDao.findByCreatedTimeBetween(start, end);
    }

    @Override
    public List<DeviceMnt> findDeviceMntByUpdatedTimeBetween(LocalDateTime start, LocalDateTime end) {
        return DeviceMntDao.findByUpdatedTimeBetween(start, end);
    }

    @Override
    public List<DeviceMnt> findDeviceMntByIsDeleted(Boolean isDeleted) {
        return DeviceMntDao.findByIsDeleted(isDeleted);
    }

    @Override
    @Transactional
    public void addDeviceMnt(DeviceMnt deviceMnt) {
        deviceMnt.setCreatedTime(LocalDateTime.now());
        deviceMnt.setUpdatedTime(LocalDateTime.now());
        deviceMnt.setIsDeleted(false);
        deviceMnt.setCreatedBy(SecurityUtils.getUser().getUserId());
        deviceMnt.setDate_time(LocalDateTime.now());
        System.out.println(deviceMnt);
        DeviceMntDao.save(deviceMnt);
    }

    @Override
    @Transactional
    public void deleteDeviceMnt(Integer id) {
        DeviceMntDao.deleteById(id);
    }

    @Override
    public DeviceMnt findLatestRecord(Integer deviceId) {
        Sort sort = Sort.by(Sort.Direction.DESC, "endTime");
        PageRequest pageRequest = PageRequest.of(0, 1, sort);
        DeviceMnt deviceMnt = new DeviceMnt();
        deviceMnt.setDeviceId(deviceId);
        Example<DeviceMnt> example = Example.of(deviceMnt);
        Page<DeviceMnt> latestData = DeviceMntDao.findAll(example,pageRequest);
        return latestData.stream().findFirst().orElse(null);

    }
}